package com.flute.search.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.flute.framework.Flute;
import com.flute.framework.FluteMonitor;
import com.flute.framework.exception.ConfigurationParseException;
import com.flute.framework.monitor.EventLogger;
import com.flute.framework.monitor.MonitedValue;
import com.flute.search.bean.Search;
import com.flute.search.bean.Searcher;
import com.flute.search.constants.SearchServiceConstants;
import com.flute.search.util.Constant;
import com.flute.search.util.XmlObjectUtil;
import com.flute.tools.util.ExceptionUtil;

public class EnterSearchService extends HttpServlet {

	private static final long serialVersionUID = 5488881706680767974L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding(SearchServiceConstants.CHARSET_UTF8);
		// 得到所有的搜索器
		String[] types = null;
		try {
			types = Flute.getInstance().getAllSearchers();
		} catch (ConfigurationParseException e) {
			error("配置解析器异常:" + ExceptionUtil.getExceptionContent(e));
			request.setAttribute("exception", "配置解析器异常");
			request.getRequestDispatcher("exception.jsp").forward(request,
					response);
			return;
		}
		Searcher xmlSearcher = xmlToSearcher();
		List<Search> searches = xmlSearcher.getSearcher(types);
		request.setAttribute("searches", searches);
		request.getRequestDispatcher("view.jsp").forward(request, response);
	}
	

	private Searcher xmlToSearcher() {
		String xml = XmlObjectUtil.readXml(Constant.SEARCHER_ALIAS_XMLPATH);
		return XmlObjectUtil.fromXml(Searcher.class, xml);
	}

	private void error(String message) {
		EventLogger.error(new MonitedValue(message), FluteMonitor
				.getSearcherKey());
	}

}
